<template>
	<view class="container">
		<view class="loading" v-if="loading">
			<u-loading></u-loading>
		</view>
		<view class="wrap" v-else>
			<view class="u-tabs-box">
				<u-tabs-swiper activeColor="#FF4E47" ref="tabs" :list="list" :current="current" @change="change" :is-scroll="false"
				 swiperWidth="750"></u-tabs-swiper>
			</view>
			<swiper @change="swiperChange" class="swiper-box" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
				<swiper-item class="swiper-item" v-for="(item,idx) in list" :key="idx">
					<scroll-view scroll-y style="height: 100%;width: 100%;" @scrolltolower="reachBottom">
						<view class="page-box">
							<view v-if="orderList[idx] == ''">
								<view class="centre">
									<image :src="appletImgUrl+'no-order.png'" mode=""></image>
									<view class="explain">
										空空如也！
									</view>
									<navigator url="/pages/tabBar/index/index" open-type="switchTab" class="btn">随便逛逛</navigator>
								</view>
							</view>
							<view class="" v-else style="padding-top: 20rpx;">
								<view class="order" v-for="(res, indexs) in orderList[idx]" :key="indexs">
									<view class="top">
										<view class="left">
											<u-icon :name="appletImgUrl+'order-store-icon.png'" :size="30"></u-icon>
											<view class="store">{{ res.storeName }}</view>
											<!-- <u-icon name="arrow-right" color="rgb(203,203,203)" :size="26"></u-icon> -->
										</view>
										<block v-if="res.groupBuyingListId && res.status == 20">
											<view class="right" v-if="res.groupBuyingList.status == 10">待分享，还差{{ res.groupBuyingList.neededUserCount }}人拼成</view>
											<view class="right" v-if="res.groupBuyingList.status == 20 || res.groupBuyingList.status == 15">抢购成功，待发货</view>
										</block>
										<block v-else>
											<view class="right">{{ status(res) }}</view>
										</block>
									</view>
									<view class="item" @click="orderDetail(indexs)" v-for="(items, index) in res.items" :key="items.id">
										<view class="left">
											<image :src="items.goodsPhoto" mode="aspectFill"></image>
										</view>
										<view class="content">
											<view class="title u-line-2">{{ items.goodsName }}</view>
											<view class="type">{{ items.goodsSkuName }}</view>
											<!-- <view class="delivery-time">下单时间：{{ item.createTime }}</view> -->
										</view>
										<view class="right">
											<view class="price">
												￥{{items.totalPrice}}
												<!-- ￥{{ priceInt(item.totalPrice) }}
												<text class="decimal">.{{ priceDecimal(item.totalPrice) }}</text> -->
											</view>
											<view class="number">x{{ items.goodsCount }}</view>
										</view>
									</view>
									<view class="total">
										共{{ totalNum(res.items) }}件商品 合计:
										<text class="total-price">
											￥{{ priceInt(totalPrice(res.items)) }}.
											<text class="decimal">{{ priceDecimal(totalPrice(res.items)) }}</text>
										</text>
									</view>
									<view class="bottom">
										<block v-if="res.status == 10">
											<view class="btn" @click="show = true;orderScene='cancel';orderItem = res;content='确认取消该笔订单吗？'">取消订单</view>
											<view class="btn" @click="pay(res)">去付款</view>
										</block>

										<block v-if="res.status == 30">
											<!-- <navigator :url="`/pages/webView/webView?url=https://m.kuaidi100.com/index_all.html&type=${res.shipCompany}&postid=${res.shipCode}`"
											 class=" btn" v-if="res.shipCode">查看物流</navigator> -->
											<view @click="warning" class="btn" v-if="res.shipCode">查看物流</view>
											<view class="btn" @click="show = true;orderScene='receivingGoods';orderItem = res;content='确认已收到宝贝吗？'">确认收货</view>
										</block>

										<block v-if="res.status == 20 && res.groupBuyingListId && (res.groupBuyingList.status == 15 || res.groupBuyingList.status == 20)">
											<navigator :url="`/pages/user/afterSale/afterSale?orderNumber=${res.orderNumber}&type=refund`" class="btn">申请退款</navigator>
										</block>

										<block v-if="res.status == 20 && !res.groupBuyingListId">
											<navigator :url="`/pages/user/afterSale/afterSale?orderNumber=${res.orderNumber}&type=refund`" class="btn">申请退款</navigator>
										</block>

										<block v-if="res.status == 20 && res.groupBuyingListId && res.groupBuyingList.status == 10">
											<view @click="setGroupCache(res.groupBuyingListId)" class="btn">邀请好友</view>
										</block>

										<block v-if="res.status == 40">
											<navigator :url="`/pages/user/afterSale/afterSale?orderNumber=${res.orderNumber}&type=returnGoods`" class=" btn">申请售后</navigator>
											<view class=" btn" @click="$u.route('/pages/user/evaluate/evaluate',{orderNumber:res.orderNumber})">去评价</view>
										</block>
										<block v-if="res.status == 70 || res.status == 65">
											<navigator :url="`/pages/user/afterSale/afterSale?orderNumber=${res.orderNumber}`" class=" btn">售后详情</navigator>
										</block>
									</view>
								</view>
								<u-loadmore v-if="orderList[idx].length >=10" :status="loadStatus[idx]" bgColor="#f2f2f2"></u-loadmore>
								<u-loadmore v-else status="nomore" bgColor="#f2f2f2"></u-loadmore>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		<u-modal show-cancel-button confirm-color="#FF4D46" v-model="show" @confirm="confirm" :content="content"></u-modal>
		<view class="" style="height: 100rpx;overflow: hidden;">
			<!-- <u-tabbar :show="tabBarState" inactive-color="#A5A4A4" active-color="#333333" icon-size="36"
			 :list="tabBarList" mid-button mid-button-size="104" :border-top="false">
			</u-tabbar> -->
		</view>
	</view>
</template>

<script>
import {appletImgUrl} from "@/common/config.js"
	export default {
		onReady() {
			this.$nextTick(() => {
				this.tabBarState = true
			})
		},
		data() {
			return {
				appletImgUrl:appletImgUrl,
				content: '',
				tabBarState: false,
				show: false,
				loading: true,
				orderScene: '',
				orderList: [
					[],
					[],
					[],
					[],
					[]
				],
				dataList: [],
				// tabBarList: [{
				// 		"pagePath": "/pages/tabBar/index/index",
				// 		"iconPath": "/static/index-tab.png",
				// 		"selectedIconPath": "/static/index-tabActive.png",
				// 		"text": "抢购商城"
				// 	},
				// 	{
				// 		"pagePath": "/pages/tabBar/shop/shop",
				// 		"iconPath": "/static/shop-tab.png",
				// 		"selectedIconPath": "/static/shop-tabActive.png",
				// 		"text": "附近店铺",
				// 	},
				// 	{
				// 		iconPath: "/static/main-tab-bar-icon.png",
				// 		selectedIconPath: "/static/main-tab-bar-icon.png",
				// 		pagePath: "/pages/tabBar/sceneSocialContact/sceneSocialContact",
				// 		midButton: true
				// 	},
				// 	{
				// 		"pagePath": "/pages/tabBar/order/order",
				// 		"iconPath": "/static/order-tab.png",
				// 		"selectedIconPath": "/static/order-tabActive.png",
				// 		"text": "我的订单"
				// 	},
				// 	{
				// 		"pagePath": "/pages/tabBar/my/my",
				// 		"iconPath": "/static/my-tab.png",
				// 		"selectedIconPath": "/static/my-tabActive.png",
				// 		"text": "个人中心"
				// 	}
				// ],
				list: [{
						name: '全部',
						status: [0, 10, 20, 30, 40, 50, 60, 65, 70, 80]
					},
					{
						name: '待付款',
						status: [10]
					},
					{
						name: '待发货',
						status: [20]
					},
					{
						name: '待收货',
						status: [30]
					},
					{
						name: '已完成',
						status: [60]
					}
				],
				current: 0,
				swiperCurrent: 0,
				tabsHeight: 0,
				orderItem: '',
				dx: 0,
				loadStatus: ['loadmore', 'loadmore', 'loadmore', 'loadmore', 'loadmore'],
			};
		},
		onLoad(options) {
			// this.current = options.current
			// this.swiperCurrent = options.current
			this.pageNo = 1
			// this.scene = options.scene
		},
		onShow() {
			if (!uni.getStorageSync('userToken')) {
				this.loading = false
				return
			}
			this.getOrderList(this.current, 'cover', () => {
				this.loading = false
			});
		},
		computed: {
			// 价格小数
			priceDecimal() {
				return val => {
					if (val !== parseInt(val)) return val.slice(-2);
					else return '00';
				};
			},
			// 价格整数
			priceInt() {
				return val => {
					if (val !== parseInt(val)) return val.split('.')[0];
					else return val;
				};
			}
		},
		onPullDownRefresh() {
			if (!uni.getStorageSync('userToken')) {
				setTimeout(() => {
					uni.stopPullDownRefresh()
				}, 1000)
				return
			}
			this.pageNo = 1
			this.loadStatus.splice(this.current, 1, "loadmore")
			this.getOrderList(this.current)
			this.$nextTick(() => {
				uni.stopPullDownRefresh()
			})
		},
		onUnload() {
			if (this.scene == 'pay') {
				uni.navigateBack({
					delta: 2
				})
			}
		},
		methods: {
			warning() {
				uni.showToast({
					title: '小程序暂不支持查看物流信息，请前往App查看该订单',
					icon: 'none'
				})
			},
			setGroupCache(groupBuyingListId) {
				this.$u.route('/pages/user/inviteFriends/inviteFriends', {
					groupBuyingListId: groupBuyingListId
				})
			},
			pay(item) {
				this.$u.route('/pages/purchase/pay/pay', {
					money: item.totalPrice,
					data: JSON.stringify({
						orderNumbers: [item.orderNumber]
					})
				});
				// return
				// const self = this
				// let index = this.orderList[this.current].findIndex(index => index.orderNumber == item.orderNumber)
				// this.$u.post('orderform/payOrder', {
				// 	channel: 3,
				// 	openId: uni.getStorageSync('openId'),
				// 	payType: 'MINI_PAY',
				// 	orderNumbers: item.items.map(number => {
				// 		return number.orderNumber
				// 	})
				// }).then(res => {
				// 	let payStr = JSON.parse(res.payStr)
				// 	uni.requestPayment({
				// 		provider: 'wxpay',
				// 		timeStamp: payStr.timeStamp,
				// 		nonceStr: payStr.nonceStr,
				// 		package: payStr.package,
				// 		signType: payStr.signType,
				// 		paySign: payStr.paySign,
				// 		success: function(res) {
				// 			console.log('success:' + JSON.stringify(res));
				// 			uni.showToast({
				// 				title: '支付成功！'
				// 			})
				// 			self.orderList[self.current][index].status = 20
				// 		},
				// 		fail: function(err) {
				// 			uni.showToast({
				// 				title: '支付失败',
				// 				icon: 'none'
				// 			})
				// 		}
				// 	});
				// })
			},
			confirm() {
				let index = this.orderList[this.current].findIndex(item => item.orderNumber == this.orderItem.$orig.orderNumber)
				if (this.orderScene == 'cancel') {
					this.$u.get('orderform/userCancel/' + this.orderItem.$orig.orderNumber).then(res => {
						uni.showToast({
							title: '订单已取消'
						})
						this.orderList[this.current][index].status = 0
					})
				}
				if (this.orderScene == 'receivingGoods') {
					this.$u.get('orderform/userreceipt/' + this.orderItem.$orig.orderNumber).then(res => {
						uni.showToast({
							title: '收货成功'
						})
						this.orderList[this.current][index].status = 40
					})
				}
			},
			status(res) {
				switch (res.status) {
					case 10:
						return '待付款'
						break
					case 20:
						return '待发货'
						break
					case 30:
						return '待收货'
						break
					case 60:
						return '已完成'
						break
					case 0:
						return '订单已取消'
						break
					case 40:
						return '已收货'
						break
					case 50:
						return '评价已完成'
						break
					case 70:
						// return '异常售后处理完成'
						return '售后已完成'
						break
					case 80:
						return '退款'
						break
					case 65:
						return '申请售后中'
						break
				}
			},
			orderDetail(index) {
				this.$u.route('/pages/user/orderDetail/orderDetail', {
					orderNumber: this.orderList[this.current][index].orderNumber
				});
			},
			reachBottom() {
				if (this.orderList[this.current] != '') {
					if (this.loadStatus[this.current] == 'nomore') return
					this.loadStatus.splice(this.current, 1, "loading")
					this.pageNo++
					this.getOrderList(this.current, 'superposition')
				}
			},
			// 页面数据
			getOrderList(idx, update = 'cover', callback = () => {}) {
				// return
				this.$u.post('orderform/orderList', {
					pageNo: this.pageNo,
					pageSize: 10,
					orderType: 1,
					statusList: this.list[idx].status
				}).then(res => {
					callback()
					if (res.list) {
						res.list.forEach(item => {
							item.items.forEach(items => {
								let transformationArray = items.goodsPhoto.split(',')
								items.goodsPhoto = this.imageURL + transformationArray[0]
							})
						})
						this.dataList = res.list
						if (update == 'cover') {
							this.orderList[idx] = [...res.list];
						} else {
							this.orderList[idx] = [...this.orderList[idx], ...res.list];
						}
						this.loadStatus.splice(this.current, 1, 'loadmore')
					} else {
						this.loadStatus.splice(this.current, 1, "nomore")
					}
				}).catch(error => {
					callback()
				})
			},
			// 总价
			totalPrice(item) {
				let price = 0;
				item.map(val => {
					price += parseFloat(val.totalPrice);
				});
				return price.toFixed(2);
			},
			// 总件数
			totalNum(item) {
				let num = 0;
				item.map(val => {
					num += val.goodsCount;
				});
				return num;
			},
			// tab栏切换
			change(index) {
				this.swiperCurrent = index;
			},
			swiperChange({
				detail: {
					current
				}
			}) {
				this.pageNo = 1
				// this.loadStatus.splice(current, 1, "loadmore")
				this.getOrderList(current);
			},
			transition({
				detail: {
					dx
				}
			}) {
				this.$refs.tabs.setDx(dx);
			},
			animationfinish({
				detail: {
					current
				}
			}) {
				this.$refs.tabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			}
		}
	};
</script>

<style>
	/* #ifndef H5 */
	page {
		height: 100%;
		background-color: #f2f2f2;
	}

	/* #endif */
</style>

<style lang="scss">
	.loading {
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	page {
		height: 100%;
		display: flex;
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		flex-direction: column;
		box-sizing: border-box;
	}

	.container {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.page-box {
		padding-bottom: 20rpx;
	}

	.order {
		width: 710rpx;
		background-color: #ffffff;
		margin: 20rpx auto;
		border-radius: 20rpx;
		box-sizing: border-box;
		padding: 20rpx;
		font-size: 28rpx;

		&:first-child {
			margin-top: 0;
		}

		.top {
			display: flex;
			justify-content: space-between;

			.left {
				display: flex;
				align-items: center;

				.store {
					margin: 0 10rpx;
				}
			}

			.right {
				color: $u-type-warning-dark;
			}
		}

		.item {
			display: flex;
			margin: 20rpx 0 0;

			.left {
				margin-right: 20rpx;

				image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 10rpx;
				}
			}

			.content {
				flex: 1;

				.title {
					font-size: 28rpx;
					line-height: 50rpx;
				}

				.type {
					margin: 10rpx 0;
					font-size: 24rpx;
					color: $u-tips-color;
				}

				.delivery-time {
					// color: #e5d001;
					color: rgb(255, 78, 71);
					font-size: 24rpx;
					word-break: break-all;
				}
			}

			.right {
				margin-left: 10rpx;
				padding-top: 20rpx;
				text-align: right;

				.decimal {
					font-size: 24rpx;
					margin-top: 4rpx;
				}

				.number {
					color: $u-tips-color;
					font-size: 24rpx;
				}
			}
		}

		.total {
			margin-top: 20rpx;
			text-align: right;
			font-size: 24rpx;

			.total-price {
				font-size: 32rpx;
			}
		}

		.bottom {
			display: flex;
			padding: 0 10rpx;
			justify-content: flex-end;
			align-items: center;

			.btn {
				line-height: 52rpx;
				width: 160rpx;
				border-radius: 26rpx;
				border: 2rpx solid $u-border-color;
				font-size: 26rpx;
				text-align: center;
				margin-top: 40rpx;
				color: $u-type-info-dark;
				margin-right: 30rpx;

				&:last-child {
					margin-right: 0;
					color: #FFFFFF;
					border: none;
					background: linear-gradient(-90deg, #FF3868, #FC6161);
				}
			}

			.evaluate {}
		}
	}

	.centre {
		text-align: center;
		// padding: 200rpx 0;
		padding-top: 200rpx;
		font-size: 32rpx;

		image {
			width: 340rpx;
			height: 340rpx;
			// border-radius: 50%;
			margin-bottom: 20rpx;
		}

		// .tips {
		// 	font-size: 24rpx;
		// 	color: #999999;
		// 	margin-top: 20rpx;
		// }

		.btn {
			margin: 30rpx auto;
			width: 200rpx;
			border: 1px solid #F39E22;
			border-radius: 10rpx;
			line-height: 64rpx;
			background-color: #FFFFFF;
			color: #F39E22;
			font-size: 26rpx;
			// background: linear-gradient(270deg, rgba(249, 116, 90, 1) 0%, rgba(255, 158, 1, 1) 100%);
		}
	}

	.wrap {
		display: flex;
		flex: 1;
		flex-direction: column;
		// height: calc(100vh - 50px);
		// height: 100%;
		width: 100%;
	}

	.swiper-box {
		flex: 1;
	}

	.swiper-item {
		height: 100%;
	}
</style>
